from flask import Flask, render_template, request, redirect, url_for, make_response, jsonify
from gevent import pywsgi
from werkzeug.utils import secure_filename
import os
import cv2
import time
from sys import argv
from datetime import timedelta
import subprocess
import shlex


def allowed_file(filename):
    # return '.' in filename and filename.rsplit('.', 1)[1] in {'png', 'PNG', 'Png'}
    return '.' in filename and filename.rsplit('.', 1)[1] in {'png', 'PNG', 'Png', 'jpg', 'JPG'}

 
app = Flask(__name__)
app.send_file_max_age_default = timedelta(seconds=1)  # 静态文件缓存过期时间

base_path = os.path.dirname(__file__)  # 当前文件所在路径


def process_image():
    im = cv2.imread(os.path.join(base_path, 'input1', '1.jpg'))
    cv2.imwrite(os.path.join(base_path, 'input1', 'test', '1.png'), cv2.hconcat([im, im]))
    cmd = "python3 test.py --dataroot ./input1 --results_dir ./result1 --name no13study --model pix2pix --direction AtoB --gpu_ids -1"
    proc = subprocess.Popen(shlex.split(cmd))
    proc.wait(30)
    im = cv2.imread(os.path.join(base_path, 'result1', 'no13study', 'test_latest', 'images', '1_fake_B.png'))
    cv2.imwrite(os.path.join(base_path, 'input2', 'test', '1.png'), cv2.hconcat([im, im]))
    cmd = "python3 test.py --dataroot ./input2 --results_dir ./result2 --name no14study --model pix2pix --direction AtoB --gpu_ids -1"
    proc = subprocess.Popen(shlex.split(cmd))
    proc.wait(30)
    proc1 = subprocess.Popen(shlex.split("cp input1/1.jpg static/1.jpg"))
    proc2 = subprocess.Popen(shlex.split("cp result1/no13study/test_latest/images/1_fake_B.png static/2.png"))
    proc3 = subprocess.Popen(shlex.split("cp result2/no14study/test_latest/images/1_fake_B.png static/3.png"))
    proc1.wait(1)
    proc2.wait(1)
    proc3.wait(1)

 
@app.route('/', methods=['POST', 'GET'])  # 添加路由
def upload():
    if request.method == 'POST':
        f = request.files['file']
 
        # if not (f and allowed_file(f.filename)):
        #     return jsonify({"error": 1001, "msg": "use jpg"})

        # upload_path = os.path.join(base_path, 'photo', secure_filename(f.filename))
        upload_path = os.path.join(base_path, 'input1', '1.jpg')
        f.save(upload_path)

        process_image()

        return render_template('result.html', val1=time.time())
 
    return render_template('upload.html')
 
 
if __name__ == '__main__':
    if len(argv) > 1 and argv[1] == 'debug':
        app.debug = True
        app.run(host='0.0.0.0', port=16888, debug=True)
    else:
        server = pywsgi.WSGIServer(('0.0.0.0', 16888), app)
        server.serve_forever()
